package com.iflytek.uoamp.notify.mail.format;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.iflytek.uoamp.common.notify.constant.ConstField;
import com.iflytek.uoamp.common.notify.format.Formatter;
import com.iflytek.uoamp.common.notify.obj.Contact;
import com.iflytek.uoamp.common.notify.obj.Content;
import com.iflytek.uoamp.common.notify.obj.Notification;
import com.iflytek.uoamp.common.notify.util.LogbackInstance;
import com.iflytek.uoamp.common.notify.util.NotifyUtils;

public abstract class FixedMailFormatter implements Formatter{
	
    protected static final String DATASTART = "<!-- DATA START -->";
    protected static final String DATAEND = "<!-- DATA END -->";
    protected static final String PRINCIPALSTART = "<!-- PRINCIPAL DATA START -->";
    protected static final String PRINCIPALEND = "<!--PRINCIPAL DATA END -->";
    protected static final String PRINCIPALSTRUCTSTART="<!-- PRINCIPAL STRUCT START -->";
    protected static final String PRINCIPALSTRUCTEND="<!-- PRINCIPAL STRUCT END -->";
    protected static final String SINGLESTART = "<!-- SINGLE START -->";
    protected static final String SINGLEEND = "<!-- SINGLE END -->";
    private static final String PRINCIPALCONTACTFLAG = "principal_contact_flag";
    protected static final String SEPARATOR = "@@";
    
    protected String remark = null;
    
    private static final Logger logger = LogbackInstance.getInstance().getLogger(FixedMailFormatter.class);
    
    public String getTitle(List<?> contents) {
        Content content = (Content)contents.get(0);
        String output = content.getOutput();
        
        return NotifyUtils.getAttributeValue(output, "subject");
    }
    
    public String getContent(String text) {
        int pos = text.indexOf("@@");
        if(pos != -1) {
            return text.substring(pos + 2);
        } else {
            return text;
        }
    }
    
    protected static String getTemplate(String templateName)  {
        
    	logger.info("get Mali template !!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    	//InputStream inputStream = FixedMailFormatter.class.getResourceAsStream("/template/" + templateName);
    	InputStream inputStream = null;
		try {
			URL url = Thread.currentThread().getContextClassLoader().getResource("");
			//获取根目录/iflytek/uoamp/uoampnotify/conf
			String path = url.getPath();
			logger.info("send mail root path ==========================="+path);
			path = path+"template/";
			inputStream = new FileInputStream(path+templateName);
			logger.info("MailFormatter is ======================="+inputStream);
			Scanner scanner = new Scanner(inputStream, ConstField.UTF8);
			StringBuilder content = new StringBuilder();
	        
	        while(scanner.hasNextLine()) {
	            content.append(scanner.nextLine());
	        }
	        scanner.close();
	        logger.info("send mail from getTemplate content =================="+content.toString());
	        return content.toString();
			
		} catch (FileNotFoundException e) {
			logger.error("getTemplate error====================="+e.getMessage(), e);
		} finally {
			if(inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    	
        return "";
    }
    
    

    /**
     * 获取整张模板内容中以<!-- DATA START -->开始并以<!-- DATA END -->结束的数据模板
     * 该模板通常用于格式化表格中的一列数据
     * @param template 模板的文件名
     * @return
     */
    protected String getDataTemplate(String template) {
        String rowTemplate = getRowTemplate(template);
        
        if(rowTemplate == null) {
            return null;
        }
        
        String singleData = null;
        if((singleData = getBlock(rowTemplate, SINGLESTART, SINGLEEND)) == null) {
            return rowTemplate;
        } else {
            return rowTemplate.replace(singleData, "");
        }
    }
    
    protected String getRowTemplate(String template) {
        return getBlock(template, DATASTART, DATAEND);
    }

    protected String getPrincipalTemplate(String template) {
        return getBlock(template, PRINCIPALSTART, PRINCIPALEND);
    }
    
    /**
     * 使用replacement字符串替换字符串content中存在的replaced字符串,如果replacement字符串为空或为null
     * 则使用空字符串作为默认值,如果replaced字符串为空字符串则不做任何处理直接返回
     * @param content
     * @param replaced 需要被替换的字符串
     * @param replacement 替换字符串
     */
    protected void replace(StringBuilder content, String replaced, String replacement) {
        if(StringUtils.isBlank(replaced)) {
            return ;
        }
        
        /*替换字段不存在则以空字符串作为替换值 */
        replacement = (StringUtils.isBlank(replacement)) ? "" : replacement;
        int startPos = content.indexOf(replaced);
        int endPos = startPos + replaced.length();
        
        if(startPos != -1 && endPos != -1) {
            content.replace(startPos, endPos, replacement);
        }
    }
    
    protected void fillAllData(StringBuilder content, String data) {
        fillAll(content, data,DATASTART, DATAEND);
    }
    
    protected void fillAll(StringBuilder content, String data, String start, String end) {
        int startPos = content.indexOf(start);
        int endPos = content.indexOf(end) + end.length();
        
        content.replace(startPos, endPos, data);
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    /**
     * 根据start和end边界符获取template模板中粒度更为细小的模板内容,该函数通常用作驱动函数
     * @param template 模板内容
     * @param start 边界开始字符串
     * @param end 边界结束字符串
     * @return
     */
    protected String getBlock(String template, String start, String end) {
        int startPos = template.indexOf(start);
        int endPos = template.indexOf(end);
        
        if(startPos != -1 && endPos != -1) {
            return template.substring(startPos, endPos + end.length());
        } else {
            return null;
        }
    }


    /****
     * 追加组件负责人表格
     * @param content
     * @param notification
     */
    protected void fillPrincipalData(StringBuilder content, Notification notification) {
        String block = getBlock(content.toString(), PRINCIPALSTART, PRINCIPALEND);
        if (!StringUtils.isEmpty(block)) {
            StringBuilder data= new StringBuilder();
            List<Contact> contacts = notification.getContacts();
            for (Contact contact : contacts) {
                if (contact.getExtend().containsKey(PRINCIPALCONTACTFLAG)) {
                    data.append(block.replace("${Principal}",contact.getName())
                            .replace("${PMail}", contact.getEmail())
                            .replace("${PTel}", contact.getPhone()));
                }
            }

            if (!StringUtils.isEmpty(data.toString())) {
                fillAll(content, data.toString(), PRINCIPALSTART, PRINCIPALEND);
            } else {
                //如果没有组件联系人信息则置空组件负责人表格
                fillAll(content, "", PRINCIPALSTRUCTSTART, PRINCIPALSTRUCTEND);
            }
        }
    }

    /**
     * 格式化传入的content列表,将列表转换为按照一定格式约束的HTML表格,对于不同的
     * content类型,pretty函数读取不同的邮件模版并返回不同的表格形式
     * @param contents content列表
     * @return 格式化后的HTML字符串
     */
    public abstract String pretty(Notification notification, List<?> contents);
}
